using System.Collections.Generic;
using Dream.FirstLevel.Interface;
using Light;
using Light.Assets.Scripts.EventManager;
using UnityEngine;
using Random = UnityEngine.Random;

//mao 24-11-23 05:38
namespace Dream.FirstLevel.Base
{
    /// <summary>
    ///     提出需求的老板
    /// </summary>
    public abstract class BossBase : MonoBehaviour, INeed
    {
        [SerializeField] private string name;

        [SerializeField] private float time; //老板的耐心

        [SerializeField] private RectTransform timeDownUIRectTransform; //倒计时的UI控制
        [SerializeField] private SpriteRenderer bossSpriteRenderer;

        public ProductList _productListGo;

        [Header("提出需求的最小间隔")] [SerializeField] protected float minWaitTime;

        [Header("提出需求的最大间隔")] [SerializeField] protected float maxWaitTime;

        /// <summary>
        ///     派发任务时的音效
        /// </summary>
        [SerializeField] private AudioClip productCreateClip;

        /// <summary>
        ///     完成单个任务奖励等待时间
        /// </summary>
        private readonly float SingleProductRewardTime = 3;

        //记录该Boss有多少product，最后给判断任务完成与否使用
        //在ProductList中不可以使用List的Count来判断任务全部完成与否
        protected int _bossProductAmount;

        protected MultipleTimer _multipleTimer; //自定义的倒计时

        protected List<ProductBase> _products = new();

        private int curIndex; //当前发起的任务到了哪一个

        //判定是否boss开启倒计时
        private bool isBossTimeDown;

        /// <summary>
        ///     往下就是碰撞检查
        /// </summary>
        private bool isTouchingPlayer;

        private Collider2D playerCollider;

        /// <summary>
        ///     boss创建要发送给Player的product缓冲
        /// </summary>
        protected List<ProductBase> productsCreateCache;

        private float startTime;

        protected virtual void Awake()
        {
            timeDownUIRectTransform = transform.Find("Canvas/TimeDown/Background/Time").GetComponent<RectTransform>();
            bossSpriteRenderer = GetComponent<SpriteRenderer>();
        }

        protected virtual void Start()
        {
            _bossProductAmount = productsCreateCache.Count;
        }


        protected virtual void Update()
        {
            if (isBossTimeDown)
            {
                if (Time.time - startTime > time)
                    SuccessOrFailJudgement();
                else UpdateTimeDown(Time.time - startTime);
            }

            //检测
            if (Input.GetKeyDown(KeyCode.J) && isTouchingPlayer)
                Need(playerCollider.GetComponentInChildren<ProductList>());
        }

        private void OnTriggerEnter2D(Collider2D other)
        {
            if (other.CompareTag("Player"))
            {
                isTouchingPlayer = true;
                playerCollider = other;
            }
        }

        private void OnTriggerExit2D(Collider2D other)
        {
            if (other.CompareTag("Player"))
            {
                isTouchingPlayer = false;
                playerCollider = null;
            }
        }


        //mao 24-11-23 06:10
        /// <summary>
        ///     满足需求
        /// </summary>
        public virtual void Need(ProductList productList)
        {
            List<ProductBase> tempWorker = new();
            List<ProductBase> tempBoss = new();

            foreach (var productBase in productList.productsList)
            foreach (var @base in _productListGo.productsList)
                if (!@base.isFinished && productBase.GetType().Name == @base.GetType().Name &&
                    productBase.isComplated)
                {
                    if (tempWorker.Contains(productBase)) continue;
                    productBase.Success();
                    tempWorker.Add(productBase);
                    tempBoss.Add(@base);
                    @base.isFinished = true;
                }

            foreach (var i in tempWorker) productList.RemoveProduct(i);
            tempWorker.Clear();

            foreach (var i in tempBoss) _productListGo.RemoveProduct(i);

            //根据boss的productList中删除的内容来判断本次提交了多少个任务
            AddWaitTimeAndMinusProductAmount(tempBoss.Count);
            SuccessOrFailJudgement(false);
            tempBoss.Clear();
        }

        /// <summary>
        ///     开启product生产倒计时
        /// </summary>
        protected void StartProductsCreateTimeDown()
        {
            List<float> randomkeysList = new();
            for (var i = 0; i < productsCreateCache.Count; i++)
            {
                Random.InitState((int)Time.time);
                var randomKey = Random.Range(minWaitTime, maxWaitTime);
                randomkeysList.Add(randomKey);
            }

            _multipleTimer = new MultipleTimer(randomkeysList, OnTimeDownHandle);
            _multipleTimer.StartTimer();
        }

        /// <summary>
        ///     开始Boss的耐心倒计时
        /// </summary>
        private void StartBossTimeDown()
        {
            startTime = Time.time;
            isBossTimeDown = true;
        }

        private void OnTimeDownHandle()
        {
            if (curIndex >= productsCreateCache.Count) return;

            //本身生成
            _productListGo.AddProduct(productsCreateCache[curIndex]);

            //Worlker产品生成
            using var evt = ProductCreateEvent.Get();
            evt.productName = productsCreateCache[curIndex].GetType().Name;
            EventManager.SendEvent(evt);

            curIndex++;

            AudioManager.Instance.PlaySFX(productCreateClip);

            //在第一件物品被产生的时候开始倒计时老板的耐心
            if (!isBossTimeDown) StartBossTimeDown();
        }


        //mao 24-11-23 06:02
        /// <summary>
        ///     更新UI状态
        /// </summary>
        /// <param name="time"></param>
        private void UpdateTimeDown(float time)
        {
            var left = 1 - time / this.time;
            timeDownUIRectTransform.localScale = new Vector3(1, left, 1);
        }

        /// <summary>
        ///     胜利或失败判断
        ///     <para>默认使用超时判断</para>
        /// </summary>
        /// <param name="timeOut"></param>
        private void SuccessOrFailJudgement(bool timeOut = true)
        {
            if (_bossProductAmount == 0)
            {
                gameObject.SetActive(false);
                using var evt = BossDestroyEvent.Get();
                EventManager.SendEvent(evt);
            }
            //包含超时并且其仍然持有对象
            else if (timeOut)
            {
                foreach (var productBase in _productListGo.productsList) productBase.Fail();
                gameObject.SetActive(false);
                using var evt = BossDestroyEvent.Get();
                EventManager.SendEvent(evt);
            }
        }


        //mao 24-11-26 02:43
        /// <summary>
        ///     根据完成的任务数量增加老板的耐心时间
        ///     <para>最长不能超过老板的最大耐心</para>
        /// </summary>
        /// <param name="count"></param>
        private void AddWaitTimeAndMinusProductAmount(int count)
        {
            //增加等待时间
            var addTime = SingleProductRewardTime * count;
            //超过限度的判断
            if (Time.time - startTime > addTime) startTime += addTime;
            else startTime = Time.time;

            //减少Product数量
            _bossProductAmount -= count;
        }
    }
}